package LeetCode;

public class Code437_pathSum {

    public int pathSum(TreeNode root, int sum) {
        if (root == null){
            return 0;
        }

        return dfs(root, sum) + pathSum(root.left, sum) +
                pathSum(root.right, sum);
    }

    private int dfs(TreeNode root, int target) {
        if (root == null){
            return 0;
        }
        int res = 0;
        if (target - root.val == 0){
            res += 1;
        }
        res += dfs(root.left, target - root.val) +
                dfs(root.right, target - root.val);
        return res;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(5);
        root.right = new TreeNode(-3);
        root.left.left = new TreeNode(3);
        root.left.right = new TreeNode(2);
        root.right.right = new TreeNode(11);
        root.left.left.left = new TreeNode(3);
        root.left.left.right = new TreeNode(-2);
        root.left.right.right = new TreeNode(1);
        Code437_pathSum code437_pathSum = new Code437_pathSum();
        System.out.println(code437_pathSum.pathSum(root, 8));
    }
}
